/**
 * Copyright (C), 2015-2020, XXX有限公司
 * FileName: UserService
 * Author:   sky
 * Date:     2020/4/20 10:18
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package cn.szh.service;

import cn.szh.dao.UserDao;
import cn.szh.domain.Role;
import cn.szh.domain.UserInfo;
import cn.szh.face.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author sky
 * @create 2020/4/20
 * @since 1.0.0
 */
@Service("userService")
public class UserService implements IUserService {
    //IUserService继承了UserDetailsService，实现类实现其中的loadUserByUsername方法，添加自己数据库中的用户及角色
    @Autowired
    private UserDao userDao;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userDao.findByUsername(username);

        List<Role> roles = userInfo.getRoles();
        User user=new User(userInfo.getUsername(), "{noop}" +userInfo.getPassword(),
        true,true,true,
        true,getAuthorities(roles));
        return user;
    }
    //添加用户角色认证
    public List<SimpleGrantedAuthority> getAuthorities(List<Role> roles) {
        List<SimpleGrantedAuthority> authorities=new ArrayList<SimpleGrantedAuthority>();
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" +role.getRoleName()));
        }
        return authorities;
    }
    //查询所有用户
    public List<UserInfo> findAll() {
        List<UserInfo> users = userDao.findAll();

        return users;
    }


    //查询用户信息
    public UserInfo findByid(int id){
        UserInfo userInfo= userDao.findByid(id);
        return  userInfo;
    }

    //保存用户信息
    public void save(UserInfo userInfo){
        userDao.save(userInfo);
    }
}
